package com.sky.sky_server.controller.user;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.sky.sky_common.result.Result;
import com.sky.sky_pojo.dto.DishVO;
import com.sky.sky_server.service.impl.DishServiceImpl;

import lombok.extern.slf4j.Slf4j;

@RestController("userDishController")
@RequestMapping("/user/dish")
@Slf4j
public class DishController {
    @Autowired
    private DishServiceImpl dishServiceImpl;

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    /**
     * 根据分类id查询菜品列表
     * @param categoryId
     * @return
     */
    @GetMapping("/list")
    public Result list(@RequestParam Long categoryId) {
        log.info("根据分类id查询菜品列表，categoryId：{}", categoryId);
        // 如果缓存存在则直接返回缓存中的数据
        String key = "dish_" + categoryId;
        List<DishVO> cache = (List<DishVO>)redisTemplate.opsForValue().get(key);
        if(cache != null && cache.size() > 0) {
            return Result.success(cache);
        }

        // 如果缓存不存在将查询结果写入缓存
        List<DishVO> res = dishServiceImpl.listDishVOsByCategoryId(categoryId);
        redisTemplate.opsForValue().set(key, res);
        
        return Result.success(res);
    }
}
